from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from app.routers import config, scan, files, scan_paths, move_files
import logging
import os

app = FastAPI(title="BT客户端文件检查器")

# 配置日志 - 使用logging_config.json中的配置
logger = logging.getLogger("app.main")

# 完全通过环境变量配置允许的源
import os
import re

def validate_origin(origin):
    """验证源地址格式是否有效"""
    origin = origin.strip()
    if not origin:
        return False
    
    # 允许通配符
    if origin == "*":
        return True
    
    # 验证URL格式：协议://主机[:端口]
    url_pattern = re.compile(
        r'^https?://'  # http:// 或 https://
        r'('  # 主机部分开始
        r'(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]'  # 域名
        r'|'  # 或
        r'(?:\d{1,3}\.){3}\d{1,3}'  # IPv4地址
        r'|'  # 或
        r'\[?[a-fA-F0-9]*:[a-fA-F0-9:]+\]?'  # IPv6地址
        r')'
        r'(:\d{1,5})?'  # 可选端口
        r'/?$'  # 可选斜杠
    )
    
    return bool(url_pattern.match(origin))

allowed_origins_env = os.getenv("ALLOWED_ORIGINS")
origins = [origin.strip() for origin in (allowed_origins_env or "").split(",")]
valid_origins = [origin for origin in origins if validate_origin(origin)]
allowed_origins = valid_origins if valid_origins else ["*"]
logger.info("=" * 60)
logger.info("CORS 配置详情:")
logger.info(f"环境变量 ALLOWED_ORIGINS: {allowed_origins_env or '未设置'}")
logger.info("实际生效的允许源:")
if allowed_origins == ["*"]:
    logger.info("  ⚠️  允许所有来源 (生产环境建议限制)")
elif not allowed_origins:
    logger.info("  ❌ 无有效源，已回退到允许所有来源")
else:
    logger.info(f"  允许源列表: {allowed_origins}")
logger.info("=" * 60)

app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(config.router, prefix="/api/config", tags=["配置管理"])
app.include_router(scan_paths.router, prefix="/api/scan-paths", tags=["扫描路径管理"])
app.include_router(scan.router, prefix="/api/scan", tags=["扫描操作"])
app.include_router(files.router, prefix="/api/files", tags=["文件操作"])
app.include_router(move_files.router)

@app.get("/")
async def root():
    return {"message": "BT客户端文件检查器API服务正在运行"}

# 添加错误处理
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": str(exc.detail)}
    )
